<template>
  <div class="table-detail">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>表详情 - {{ table?.table_name }}</span>
          <el-button type="primary" size="small" @click="$router.push('/monitor/tables')">返回列表</el-button>
        </div>
      </template>
      
      <div v-if="table" class="table-info">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border title="基本信息">
          <el-descriptions-item label="表名">{{ table.table_name }}</el-descriptions-item>
          <el-descriptions-item label="数据库">{{ table.database_name }}</el-descriptions-item>
          <el-descriptions-item label="数据层">
            <el-tag :class="`layer-${table.layer.toLowerCase()}`">{{ table.layer }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="table.is_active ? 'success' : 'danger'">
              {{ table.is_active ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="监控间隔">{{ table.monitor_interval }}秒</el-descriptions-item>
          <el-descriptions-item label="告警阈值">{{ table.alert_threshold }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ table.description || '暂无描述' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 数据统计 -->
        <el-descriptions :column="3" border title="数据统计" style="margin-top: 20px;">
          <el-descriptions-item label="当前行数">{{ formatNumber(latestStats?.row_count || 0) }}</el-descriptions-item>
          <el-descriptions-item label="数据大小">{{ formatDataSize(latestStats?.data_size || 0) }}</el-descriptions-item>
          <el-descriptions-item label="分区数量">{{ latestStats?.partition_count || 0 }}</el-descriptions-item>
          <el-descriptions-item label="增量数据">{{ formatNumber(latestStats?.increment_count || 0) }}</el-descriptions-item>
          <el-descriptions-item label="平均行大小">{{ latestStats?.avg_row_size ? `${latestStats.avg_row_size} B` : '-' }}</el-descriptions-item>
          <el-descriptions-item label="最后更新">{{ latestStats?.record_time ? formatTime(latestStats.record_time) : '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 数据趋势图 -->
        <el-card title="数据趋势" style="margin-top: 20px;">
          <div class="chart-container">
            <v-chart :option="chartOption" style="height: 400px;" />
          </div>
        </el-card>

        <!-- 表结构信息 -->
        <el-card title="表结构 (数据字典)" style="margin-top: 20px;">
          <el-table :data="tableSchema" border style="width: 100%">
            <el-table-column prop="column_name" label="字段名" width="150" />
            <el-table-column prop="data_type" label="数据类型" width="120" />
            <el-table-column prop="is_nullable" label="允许空值" width="100">
              <template #default="{ row }">
                <el-tag :type="row.is_nullable ? 'warning' : 'success'" size="small">
                  {{ row.is_nullable ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="is_primary_key" label="主键" width="80">
              <template #default="{ row }">
                <el-tag v-if="row.is_primary_key" type="danger" size="small">是</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="is_partition_key" label="分区键" width="80">
              <template #default="{ row }">
                <el-tag v-if="row.is_partition_key" type="warning" size="small">是</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="default_value" label="默认值" width="120" />
            <el-table-column prop="description" label="字段说明" show-overflow-tooltip />
            <el-table-column prop="ordinal_position" label="位置" width="80" />
          </el-table>
        </el-card>

        <!-- 分区信息 -->
        <el-card title="分区信息" style="margin-top: 20px;">
          <el-table :data="partitionInfo" border style="width: 100%">
            <el-table-column prop="partition_name" label="分区名" />
            <el-table-column prop="partition_value" label="分区值" />
            <el-table-column prop="row_count" label="行数" />
            <el-table-column prop="data_size" label="数据大小" />
            <el-table-column prop="last_update" label="最后更新" />
          </el-table>
        </el-card>

        <!-- 增量趋势（日/小时） -->
        <el-card style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span>增量趋势</span>
              <div>
                <el-radio-group v-model="granularity" size="small" @change="loadIncrements">
                  <el-radio-button label="day">按日</el-radio-button>
                  <el-radio-button label="hour">按小时</el-radio-button>
                </el-radio-group>
                <el-radio-group v-if="granularity === 'hour'" v-model="hourRange" size="small" style="margin-left: 10px" @change="loadIncrements">
                  <el-radio-button label="6h">6小时</el-radio-button>
                  <el-radio-button label="12h">12小时</el-radio-button>
                  <el-radio-button label="24h">24小时</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="incrementsOption" style="height: 360px;" />
          </div>
        </el-card>
      </div>

      <div v-else class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent, DataZoomComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { monitorApi } from '@/api/monitor'
import type { MonitoredTable, TableStatistics, TableSchema } from '@/types'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent, DataZoomComponent])

const route = useRoute()
const table = ref<MonitoredTable | null>(null)
const tableSchema = ref<TableSchema[]>([])
const tableStatistics = ref<TableStatistics[]>([])
const partitionInfo = ref<any[]>([])
const loading = ref(false)

// 增量趋势（日/小时）
const granularity = ref<'day' | 'hour'>('hour')
const hourRange = ref<'6h' | '12h' | '24h'>('24h')
const increments = ref<Array<{ time: string; increment: number }>>([])
const incrementsOption = computed(() => ({
  title: { text: granularity.value === 'hour' ? '每小时增量' : '每日增量', left: 'center' },
  tooltip: { trigger: 'axis' },
  grid: { left: '3%', right: '4%', bottom: '6%', containLabel: true },
  xAxis: { type: 'category', data: increments.value.map(p => p.time) },
  yAxis: { type: 'value', name: '增量' },
  dataZoom: [{ type: 'inside', start: 0, end: 100 }, { start: 0, end: 100 }],
  series: [{ name: '增量', type: 'line', smooth: true, areaStyle: {}, data: increments.value.map(p => p.increment) }]
}))

// 计算属性
const latestStats = computed(() => {
  if (tableStatistics.value.length === 0) return null
  return tableStatistics.value[tableStatistics.value.length - 1]
})

const chartOption = computed(() => ({
  title: {
    text: '数据趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function(params: any) {
      const data = params[0]
      return `${data.name}<br/>
              行数: ${formatNumber(data.value)}<br/>
              数据大小: ${formatDataSize(data.data.data_size || 0)}<br/>
              增量: ${formatNumber(data.data.increment_count || 0)}`
    }
  },
  legend: {
    data: ['行数', '数据大小', '增量数据'],
    top: 30
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: tableStatistics.value.map(s => formatTime(s.record_time, 'MM-DD HH:mm'))
  },
  yAxis: [
    {
      type: 'value',
      name: '行数',
      position: 'left'
    },
    {
      type: 'value',
      name: '数据大小(MB)',
      position: 'right',
      axisLabel: {
        formatter: (value: number) => (value / 1024 / 1024).toFixed(2)
      }
    }
  ],
  series: [
    {
      name: '行数',
      type: 'line',
      data: tableStatistics.value.map(s => ({
        value: s.row_count,
        data_size: s.data_size,
        increment_count: s.increment_count
      }))
    },
    {
      name: '数据大小',
      type: 'line',
      yAxisIndex: 1,
      data: tableStatistics.value.map(s => s.data_size || 0)
    },
    {
      name: '增量数据',
      type: 'bar',
      data: tableStatistics.value.map(s => s.increment_count)
    }
  ],
  dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 100
    },
    {
      start: 0,
      end: 100
    }
  ]
}))

const loadTableDetail = async () => {
  const tableId = parseInt(route.params.id as string)
  loading.value = true
  
  try {
    // 并行加载数据
    const [tableResponse, schemaResponse, statsResponse] = await Promise.all([
      monitorApi.getTableDetail(tableId),
      monitorApi.getTableSchema(tableId),
      monitorApi.getTableStatistics(tableId, getStartTime(), getEndTime())
    ])
    
    table.value = tableResponse.data
    tableSchema.value = schemaResponse.data
    tableStatistics.value = statsResponse.data
    
    // 模拟分区信息
    partitionInfo.value = [
      {
        partition_name: 'p20240101',
        partition_value: '2024-01-01',
        row_count: 500000,
        data_size: 102400000,
        last_update: '2024-01-15T10:00:00Z'
      },
      {
        partition_name: 'p20240102',
        partition_value: '2024-01-02',
        row_count: 520000,
        data_size: 106496000,
        last_update: '2024-01-15T10:00:00Z'
      }
    ]
    
  } catch (error) {
    console.error('Failed to load table detail:', error)
    ElMessage.error('加载表详情失败')
  } finally {
    loading.value = false
  }
}

const loadIncrements = async () => {
  const tableId = parseInt(route.params.id as string)
  try {
    const res = await monitorApi.getIncrements({ table_id: tableId, granularity: granularity.value })
    let points = res.data
    if (granularity.value === 'hour') {
      const keep = hourRange.value === '6h' ? 6 : hourRange.value === '12h' ? 12 : 24
      points = points.slice(-keep)
    }
    increments.value = points
  } catch (e) {
    console.error('Failed to load increments:', e)
  }
}

const getStartTime = () => {
  const date = new Date()
  date.setDate(date.getDate() - 7)
  return date.toISOString()
}

const getEndTime = () => {
  return new Date().toISOString()
}

const formatNumber = (num: number): string => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(2) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(2) + 'K'
  }
  return num.toString()
}

const formatDataSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatTime = (time: string, format?: string): string => {
  if (!time) return '-'
  const date = new Date(time)
  if (format === 'MM-DD HH:mm') {
    return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  }
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadTableDetail()
  loadIncrements()
})
</script>

<style scoped>
.table-detail {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-info {
  margin-top: 20px;
}

.chart-container {
  margin: 20px 0;
}

.loading-container {
  margin-top: 20px;
}
</style> 